package com.shux.common.sessionfactory;

import java.io.File;
import java.io.IOException;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.shux.common.exception.ShuxRunTimeException;
import com.shux.utils.string.StringUtil;

/**
 **********************************************
 *  描述：支持不同模块相同entity下实体的别名
 * Simba.Hua
 * 2017年6月24日
 **********************************************
**/
public class ShuxSqlSessionFactoryBean extends SqlSessionFactoryBean{
    private Logger logger = LoggerFactory.getLogger(getClass());
    private final static String CLASSPATH = "classpath*:";
    private final static String PRESUFFER = StringUtil.join("com",File.separator,"shux",File.separator);
    private static final String ROOT_PATH_SPLIT = ",";
    private static final String[] PATH_REPLACE_ARRAY = { "]" }; 
    
    public void setTypeAliasesPackage(String typeAliasesPackage){
        if (!StringUtil.isStringAvaliable(typeAliasesPackage)){//判断是否含有**
           super.setTypeAliasesPackage(typeAliasesPackage); 
           return;
        }
        ResourcePatternResolver  resolver = new PathMatchingResourcePatternResolver();
        StringBuffer typeAliasesPackages = new StringBuffer();
        try {
          for(String location : typeAliasesPackage.split(",")){
              if(StringUtil.isEmpty(location)){
                  continue;
              }
              location = StringUtil.join(CLASSPATH,location.trim().replace(".", File.separator));
              typeAliasesPackages.append(getResources(resolver,location));
          }
        } catch (IOException e) {
            logger.error("解析模糊匹配实体别名出错",e);
        }
        if(StringUtil.isEmpty(typeAliasesPackages.toString())){
            throw new ShuxRunTimeException("没有找到相关的实体类,请检查sqlSessionFactory中参数typeAliasesPackage路径");
        }
        typeAliasesPackage = replaceResult(typeAliasesPackages.toString()).replace(File.separator,".");
        super.setTypeAliasesPackage(typeAliasesPackage);
        
    }
    private String replaceResult(String resultStr) {
        for(String replaceStr : PATH_REPLACE_ARRAY){
            resultStr = resultStr.replace(replaceStr, "");
        }
        return resultStr;
    }
    /**
     * 解析所有模糊匹配的包数据
     * @param resolver
     * @param location
     * @return
     */
    private String getResources(ResourcePatternResolver resolver,String location) throws IOException{
            StringBuffer resourcePath = new StringBuffer();
            Resource[] resources = resolver.getResources(location);
            for(Resource resource : resources){
                String description = resource == null?"":resource.getDescription();
                if(StringUtil.isEmpty(description) || !description.contains(PRESUFFER)){
                    continue;
                }
                resourcePath.append(description.substring(description.indexOf(PRESUFFER))).append(ROOT_PATH_SPLIT);        
            }
            return resourcePath.toString();
    }
    
}
